<template>
  <div>
    <el-form :model="searchForm" class="demo-dynamic" ref="tableSearchRef">
      <el-row>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="(val, key) in search" :key="key">
          <el-form-item :label="val.label" :prop="val.prop"
                        :rules="[{ required: val.required, message: `${val.label}不能为空`, trigger: val.type === 'input' ? 'blur' : 'change' }]"
                        style="margin-right: 20px">
            <el-input v-model="searchForm[val.prop]" :placeholder="val.placeholder" clearable
                      v-if="val.type === 'input'" style="width: 100%"/>
            <el-date-picker v-model="searchForm[val.prop]" type="date" :placeholder="val.placeholder"
                            v-else-if="val.type === 'date'" style="width: 100%"/>
            <el-select v-model="searchForm[val.prop]" :placeholder="val.placeholder" v-else-if="val.type === 'select'"
                       style="width: 100%">
              <el-option v-for="item in val.options" :key="item.value" :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item class="table-form-btn">
            <el-button size="default" type="primary" @click="onSearch(tableSearchRef)">查询</el-button>
            <el-button size="default" type="info" class="ml10" @click="onReset(tableSearchRef)"> 重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import useModel from '@/composables/useModel'

defineOptions({
  name: 'MSearch',
  inheritAttrs: false
})
const props = defineProps({
  search: {
    type: Array,
    default: () => []
  },
  initForm: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['search', 'update:initForm'])

const searchForm = useModel(props, 'initForm', emit)

const tableSearchRef = ref()
const onSearch = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      emit('search', searchForm.value)
    } else {
      return false
    }
  })
}
// 重置
const onReset = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  emit('search', searchForm.value)
}
</script>

<style scoped lang="scss"></style>
